<template>
    <view>
        <view class="confirm-order">
            <view class="confirm-con">
                <navigator hover-class="none" url="/bundle/pages/user_address/user_address?type=1">
                    <view class="address flex bg-white">
                        <image class="icon-md m-r-20" src="/static/images/icon_address.png"></image>
                        <view class="flex-1 m-r-20">
                            <view class="black md" v-if="!address.contact">设置收货地址</view>
                            <view v-else>
                                <text class="name md m-r-10">{{address.contact}}</text>
                                <text class="phone md">{{address.telephone}}</text>
                                <view class="area sm m-t-10 lighter">
                                    {{address.province}} {{address.city}} {{address.district}} {{address.address}}
                                </view>
                            </view>
                        </view>
                        <u-icon name="arrow-right"></u-icon>
                    </view>
                </navigator>
                
                <!-- 拼团商品 -->
                <block v-if="teamId==undefined">
                    <view class="goods contain" v-for="(item,index) in shopLists" :key="index">
                        <order-shop :order-type="orderInfo.order_type" :item="item" :invoice="invoiceArr" @changeremark="changeRemark"
                            @changecoupon="changeCoupon($event,index)" @changeDeliveryType="changeDeliveryType($event,item)" :teamId="teamId" :bargainLaunchId="bargainLaunchId"></order-shop>
                    </view>
                </block>
                <!-- 其他商品 -->
                <block v-else>
                    <view class="goods contain">
                        <order-shop :order-type="orderInfo.order_type" :item="shopLists" :invoice="invoiceArr" @changeremark="changeRemark"
                             @changeDeliveryType="changeDeliveryType($event, shopLists)" :teamId="teamId" :bargainLaunchId="bargainLaunchId"></order-shop>
                    </view>
                </block>				
            </view>
			
            <view class="footer bg-white flex row-between fixed">
                <view class="all-price lg flex">
                    <text>合计：</text>
                    <view class="primary">
                        <price-format weight="500" :first-size="36" :second-size="36" :price="orderInfo.total_amount">
                        </price-format>
                    </view>
                </view>
				<loading-view v-if="loadingPay"></loading-view>
                <button class="btn br60 white" size="md" hover-class="none" @tap="onSubmitOrder">
                   <!-- <u-loading mode="circle" :show="loadingPay" /> -->
                   <text v-show="!loadingPay">立即支付</text>
                </button>
            </view>
        </view>
		
        <loading-view v-if="showLoading" background-color="transparent" :size="50"></loading-view>
        <loading-view v-if="isFirstLoading"></loading-view>
    </view>
</template>

<script>
    import {
        orderInfo,
        orderBuy,
        getOrderCoupon
    } from '@/api/order';
    import {
        teamBuy,
        teamKaiTuan
    } from '@/api/activity'
    import {
        prepay,
        getMnpNotice,
        getPayway
    } from '@/api/app';
	import {
		mapGetters
	} from 'vuex';
    import {
        wxpay,
        alipay
    } from '@/utils/pay';
	import Cache from '@/utils/cache'
    // total_amount
    export default {
        data() {
            return {
                isFirstLoading: true,
                showLoading: false,
                address: {},
                orderInfo: {},
                shopLists: [],
                addressId: '',
                useIntegral: 0,
                userRemark: [],
                couponId: [],
				gid:[],
                teamId: undefined,
                carts: [],
                type: '',
                goods: '',
                bargainLaunchId: -1,
                invoiceArr: [] ,		// 发票数组
				amount: 0,				// 支付金额
				timeout: 0,				// 倒计时间戳
				payway: '',				// 支付方式
				loadingPay: false,		// 支付处理中Loading
				order_id:'',
				from:''
            };
        },
		computed: {
			...mapGetters(['token', 'appConfig','distribution','isLogin']),
		},
        onLoad(options) {
            uni.$on("selectaddress", (e) => {
                // this.addressId = e.id;
				this.addressId = e.item.id;
				this.orderBuyFun();
            })
            // 监听发票传回的值，
            uni.$on('invoice', params => {
                const index = this.invoiceArr.findIndex(el => el.shop_id == params.shop_id)
                if ( params.del == true && this.invoiceArr.length) {
                    this.invoiceArr.splice(index, 1);
                } else {
                    if ( index == -1 ) this.invoiceArr = [...this.invoiceArr, params]
                    else this.invoiceArr.splice(index, 1, params);
                }
            })
			
            const {
                data: {
                    goods,
                    carts,
                    teamId,
                    foundId,
                    type,
			
                }
            } = this.$Route.query

            this.goods = goods
            this.bargainLaunchId = goods[0].bargain_launch_id || -1
            this.carts = carts || []
	
            this.type = type
            this.teamId = teamId
            // 参团的id，如果为空的话就是开团，如果有数据就是参团
            this.foundId = foundId || ''
			
			this.orderBuyFun();
        },
		
		onUnload() {
			uni.$off("selectaddress")
			uni.$off("payment")
			uni.$off("invoice")
		},
		
        methods: {
            // 备注
            changeRemark(e) {
				console.log(e)
                let index = this.userRemark.findIndex((item) => item.gid == e.gid)
                if (index == -1) {
                    this.userRemark.push(e)
                } else {
                    this.userRemark[index].remark = e.remark
                }
                this.userRemark = this.userRemark.filter((item) => item.remark)
            },
			
            // 选中优惠券
            changeCoupon(e, index) {
                this.couponId[index] = e
                this.orderBuyFun()
            },
			
			// 选择对应的配送方式赋值给商品中的配送方式
			changeDeliveryType(type, row) {
				row.delivery_type = type;
				for(let i=0;i<this.goods.length;i++) {
					const item = this.goods[i];
					if(row.shop_id == item.shop_id) {
						this.goods[i].delivery_type = type;
					}
				}
				this.orderBuyFun();
			},
			
            getAuthMsg() {  
                return new Promise((resolve, reject) => { // 添加 reject 以处理可能的错误  
                    getMnpNotice({  
                        scene: '103,104,105'  
                    }).then(res => {  
                        if (res.code == 1) {  
                            uni.requestSubscribeMessage({  
                                tmplIds: res.data,  
                                fail(err) {  
                                    console.log(err.errMsg);  
                                    reject(err); // 在授权失败时拒绝 Promise  
                                },  
                                success() {  
                                    resolve(); // 在授权成功时解决 Promise（注意：这里应该放在 success 回调中，而不是 complete）  
                                },  
                                complete() {  
                                    // complete 回调不是用来解决或拒绝 Promise 的最佳位置，  
                                    // 因为它无论成功还是失败都会被调用。  
                                    // 通常，我们会在 success 或 fail 中处理 Promise 的状态。  
                                }  
                            });  
                        } else {  
                            resolve(); // 如果不需要授权，则直接解决 Promise  
                        }  
                    }).catch(err => {  
                        reject(err); // 处理 getMnpNotice 可能抛出的错误  
                    });  
                });  
            },

           async onSubmitOrder() {
			   if(this.distribution.is_mnp_notice != 1){
				   await this.getAuthMsg();
			   }
				this.showLoading = true
				this.orderBuyFun('submit');
            },

            async orderBuyFun(action = 'info') {
                const {
                    userRemark,
                    useIntegral,
                    carts,
                    goods,
                    bargainLaunchId,
                    couponId,
					gid
                } = this;
                const submitObj = {
                    goods: JSON.stringify(goods),
                    address_id: this.addressId,
					gid:this.gid,	
                    cart_id: carts.join(),
                    coupon_id: couponId.filter(item => item),
                    // bargain_launch_id是砍价的判断
                    bargain_launch_id: this.bargainLaunchId == -1 ? '' : this.bargainLaunchId
                };
				console.log("submitObj111",submitObj)
				
                // 判断是不是拼团的，并且是获取订单数据
                if (this.teamId && action == 'info') {
                    delete submitObj.goods;
                    submitObj.action = 'info';
                    submitObj.item_id = this.goods[0].item_id;
                    submitObj.delivery_type = this.goods[0].delivery_type;
                    submitObj.count = this.goods[0].num;
                    submitObj.goods_id = this.goods[0].goods_id;
                    submitObj.team_id = this.teamId;
                }
                // 判断是不是拼团的，并且是提交订单
                if (this.teamId && action == 'submit') {
                    submitObj.action = 'buy';
                    submitObj.item_id = this.goods[0].item_id;
                    submitObj.delivery_type = this.goods[0].delivery_type;
                    submitObj.count = this.goods[0].num;
                    submitObj.goods_id = this.goods[0].goods_id;
                    submitObj.team_id = this.foundId;
                    submitObj.gid = this.gid;
                }
                
                if (action == 'submit') {
                    // 拿第一个店铺的 delivery_type 类型，虚拟商品不能加入购物车所以不用考虑会虚拟商品和实物商品出错
                    submitObj.delivery_type = this.shopLists[0]?.delivery_type || 0;
                    submitObj.remark = userRemark.length ? userRemark : '';
					submitObj.gid=this.gid;
					console.log("userRemark",submitObj.remark);
					console.log("gid",submitObj.gid);
                    submitObj.invoice = JSON.stringify(this.invoiceArr);
                }

                let {
                    data: orderData,
                    code: orderCode,
                    msg: orderMsg
                } = action == 'info' ? this.teamId ? await teamKaiTuan(submitObj) : await orderInfo(submitObj) : 
                this.teamId ? await teamKaiTuan(submitObj) : await orderBuy(submitObj)
                // 如果是info的话说明是获取订单数据，？用拼团的id判断当前是否是拼团，是的话调用teamKaiTuan，不是的话调用普通订单获取orderInfo
                // ：判断是不是拼团订单，是的话调用teamKaiTuan提交拼团订单，否则就是普通订单orderBuy
                
                if(orderMsg == '抱歉,库存不足') {
                    setTimeout(() => {
                        uni.navigateBack(1)
                    },500)
                }
				
                if (orderCode !== 1) return this.showLoading = false
                if (action == 'info') {
                    const {
                        shop,
                        address,
                    } = orderData
                    this.address = address
                    this.shopLists = shop
                    this.orderInfo = orderData
					this.gid=shop.map(item=>item.gid)
					//uni.removeStorageSync("gid")
                    this.$nextTick(() => {
                        this.isFirstLoading = false
                    });
                } else if (action == 'submit') {
					this.showLoading = false
					
					 this.from = orderData.type
					
					switch(this.from) {
						case 'order': this.order_id = orderData.order_id; break;
						case 'trade': this.order_id = orderData.trade_id; break;
					}
					this.initPageData()
					uni.$on('payment', params => {
						console.log("params",params)
						setTimeout(() => {
							if (params.result) {
								console.log('Jason', this)
								this.$Router.replace({
									path: '/bundle/pages/pay_result/pay_result',
									query: {
										id: params.order_id,
										from: params.from
									}
								})
							} else {
								this.$Router.replace({
									path: '/bundle/pages/user_order/user_order'
								})
							}
						}, 1 * 10)
					})
					
					
                }
            },
			
			// 初始化页面数据
			initPageData() {
				// 获取支付方式
				getPayway({
					from: this.from,
					order_id: this.order_id,
				}).then(res => {
					if (res.code != 1) throw new Error(res.msg)
					return res.data
				}).then(data => {
					this.amount = data.order_amount
					if (data.pay_way.length>1) {
						uni.navigateTo({
							url: `/bundle/pages/payment/payment?from=${this.from}&order_id=${this.order_id}`
						})
					} else{
						this.payway = data.pay_way[0]?.pay_way
						this.handlePrepay()
						// 倒计时
						const startTimestamp = new Date().getTime()
						const endTimestamp = data.cancel_time
						this.timeout = endTimestamp - (startTimestamp / 1000)
					}
					
				}).catch(err => {
					throw new Error(err)
				})
			},
			
			handlePrepay() {
				if (this.loadingPay) return
				this.loadingPay = true
				prepay({
					from: this.from,
					order_id: this.order_id,
					pay_way: this.payway,
				}).then(({ code, data }) => {
					switch(code) {
						case 1: 
							this.handleWechatPay(data); 
							break;
						case 10001: 
							this.handleAlipayPay(data); 
							break;
						case 20001: 
							this.handleWalletPay(); 
							break;
					}
				}).catch(err => {
					
				}).finally(() => {
					setTimeout(() => {
						this.loadingPay = false
					}, 500)
				})
			},
			
			handleWechatPay(data) {
				wxpay(data).then(res => {
					console.log('==handleWechatPay===res================')
					console.log(res)
					this.handPayResult(res)
				}).catch(err => {
					console.log(err)
				})
			},
			// 钱包余额支付
			handleWalletPay() {
				console.log('--handleWalletPay--支付成功')
				//余额支付成功
				this.handPayResult('success')
			},
			
			// 支付后处理
			handPayResult(result) {
					// 页面出栈
					/* //记录支付结果
					 this.result = result
					console.log("result",this.result)
					uni.navigateBack()
					this.$Router.back(1) */
					switch(result) {
						case 'success': 
							this.$Router.replace({
								path: '/bundle/pages/pay_result/pay_result',
								query: {
									id: this.order_id,
									from: this.from
								}
							}) 
							break;
						case 'fail':
						default: this.$Router.replace({
										path: '/bundle/pages/user_order/user_order'
									})
					}
				}
			
        },
        watch: {
            address(val) {
                this.addressId = val.id
            }
        }

    }
</script>
<style lang="scss" scoped>
    .confirm-order {
        .confirm-con {
            overflow: hidden;
            padding-bottom: calc(120rpx + env(safe-area-inset-bottom));

            .address {
                min-height: 164rpx;
                padding: 0 24rpx;
                border-radius: 14rpx;
                margin: 20rpx 20rpx 0;
            }

            .img-line {
                height: 1.5px;
                width: 100%;
                display: block;
            }
        }

        .price {
            padding: 28rpx 20rpx;

            .item:not(:last-of-type) {
                margin-bottom: 20rpx;
            }
        }

        .contain {
            border-radius: 14rpx;
            margin: 20rpx 20rpx 0;
            background-color: #fff;
            overflow: hidden;
        }

        .radio-group {
            display: block;
        }

        .footer {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
			z-index: 99;
            height: 100rpx;
            padding: 0 30rpx;
            box-sizing: content-box;
            padding-bottom: env(safe-area-inset-bottom);

            .btn {
				background: #00632B;
                padding: 0 50rpx;
            }
        }

    }

    // .confirm-order .van-cell:after {
    // 	border: none;
    // }

    // .goods .shop-icon {
    // 	width: 40rpx;
    // 	height: 40rpx;
    // }

    // .pop-title {
    // 	height: 100rpx;
    // 	border-bottom: 1rpx solid #F2F2F2;
    // }

    // .pop-title .title {
    // 	margin-left: 30rpx;
    // 	font-size: 34rpx;
    // 	font-weight: bold;
    // 	line-height: 36rpx;
    // }
</style>
